package com.olah.ws.service;

import cn.hutool.core.date.DateUtil;
import com.olah.common.entity.po.ws.dto.add_friend.AddFriendResponse;
import com.olah.common.entity.po.ws.dto.chat.PrivateMsg;
import com.olah.common.entity.po.ws.dto.core.WebSocketRequest;
import com.olah.ws.dao.PrivateMsgDao;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

import static com.olah.ws.service.WebSocketService.notifyPrivateMsg;

@Service
public class PrivateMsgService {

    @Resource
    private PrivateMsgDao dao;

    private static final String sayHello = "我们已经是好友了, 现在开始聊天吧";

    public void sendToUser(PrivateMsg userMsg) {
        dao.sendToUser(userMsg);
    }

    public List<PrivateMsg> readAll(int id, boolean unreadOnly) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("unread", unreadOnly);
        return dao.readAll(map);
    }

    /**
     * 添加好友之后的打招呼环节
     * @param response
     * @param userMsgService
     */
    public void doSayHello(WebSocketRequest<AddFriendResponse> response, PrivateMsgService userMsgService) {
        int receiverId = response.getReceiver().getId();
        int senderId = response.getSender().getId();
        String chatId = String.format("%d-%d", Math.min(receiverId, senderId), Math.max(receiverId, senderId));
        String time = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
        PrivateMsg userMsg1 = new PrivateMsg(null, chatId, senderId, receiverId, sayHello, time);
        userMsgService.sendToUser(userMsg1);
        notifyPrivateMsg(receiverId, null, userMsg1, "receiveMsgFromUser");

        PrivateMsg userMsg2 = new PrivateMsg(null, chatId, receiverId, senderId, sayHello, time);
        userMsgService.sendToUser(userMsg2);
        notifyPrivateMsg(senderId, null, userMsg2, "receiveMsgFromUser");
    }

    public void doRead(String chatId) {
        dao.doRead(chatId);
    }
}
